package cn.sinata.wanglin.village.activity;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.xilada.xldutils.activitys.DialogActivity;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.view.SwipeRefreshRecyclerLayout;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sinata.wanglin.MyApplication;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.adapter.MyVillageAdapter;
import cn.sinata.wanglin.adapter.NearVillageAdapter;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.model.MyVillage;
import cn.sinata.wanglin.model.Village;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import cn.sinata.wanglin.property.activity.SearchVillageActivity;

public class ChoiceVillageActivity extends DialogActivity {
    @BindView(R.id.mSwipeRefreshLayout)
    SwipeRefreshRecyclerLayout mSwipeRefreshLayout;//
    private RecyclerView.ItemDecoration defaultItemDecoration;
    private NearVillageAdapter mNearVillageAdapter;
    private ArrayList<Village> mVillages = new ArrayList<>();
    private ArrayList<MyVillage> mMyVillages = new ArrayList<>();//我的小区数据
    private MyVillageAdapter mMyVillageAdapter;
    private int pageNo = 0;
    private TextView tv_nohavevillage;//暂无我的小区
    private RecyclerView rv_myvillage;
    @Override
    protected int setContentLayout() {
        return R.layout.activity_choicevillage;
    }

    @Override
    protected void initView() {
        setCancelOnTouchOutside(false);
        defaultItemDecoration = new HorizontalDividerItemDecoration.Builder(this)
                .colorResId(com.xilada.xldutils.R.color.dividing_line_color)
                .marginResId(com.xilada.xldutils.R.dimen.activity_horizontal_margin, com.xilada.xldutils.R.dimen.activity_horizontal_margin)
                .size(1)
                .build();
        mSwipeRefreshLayout.setLayoutManager(getLayoutManager());
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshRecyclerLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pullDownRefresh();
            }

            @Override
            public void onLoadMore() {
                loadMore();
            }
        });
        mSwipeRefreshLayout.setMode(getMode());
        if (setAdapter() != null) {
            RecyclerView.Adapter adapter = setAdapter();
            mSwipeRefreshLayout.setAdapter(adapter);
        }
        setRefreshing(false);
        if (getDefaultItemDecoration() != null) {
            addItemDecoration(getDefaultItemDecoration());
        }
        getData();
        getMyVillageData();
    }
    /**
     * 是否显示无我的小区提示
     */
    private void isShowNoMyVillage() {
        if(mMyVillages==null||mMyVillages.size()==0){
            tv_nohavevillage.setVisibility(View.VISIBLE);
        }else{
            tv_nohavevillage.setVisibility(View.GONE);
        }
    }
    private  void getMyVillageData(){
        String userid= SharedPreferencesUtils.getString(Constant.SP_USERID);
        HttpManager.getMyVillage(userid)
                .subscribe(new ResultDataSubscriber<ArrayList<MyVillage>>(this) {
                    @Override
                    public void onSuccess(String msg, ArrayList<MyVillage> myvillage) {
                        mSwipeRefreshLayout.setRefreshing(false);
                        mMyVillages.clear();
                        if(myvillage!=null){
                            mMyVillages.addAll(myvillage);
                        }
                        mMyVillageAdapter.notifyDataSetChanged();
                        isShowNoMyVillage();
                    }
                });

    }

    /**
     * 获取附近的小区
     */
    void getData(){
        HttpManager.getNearbyHousing(MyApplication.lng,MyApplication.lat,pageNo)
                .subscribe(new ResultDataSubscriber<ArrayList<Village>>(this) {
                    @Override
                    public void onSuccess(String msg, ArrayList<Village> villages) {
                        mSwipeRefreshLayout.setRefreshing(false);
                        if (pageNo == 0) {
                            mVillages.clear();
                        }
                        if (villages.size() == 0) {
                            if (pageNo == 0) {
                                setLoadMoreText("暂无数据");
                            } else {
                                pageNo --;
                                setLoadMoreText("没有更多了");
                            }
                        }
                        mVillages.addAll(villages);
                        mNearVillageAdapter.notifyDataSetChanged();
                    }
                });

    }
    private RecyclerView.Adapter setAdapter() {
        mNearVillageAdapter = new NearVillageAdapter(mVillages);
        View headerView = View.inflate(mContext, R.layout.header_choicevillage_layout,null);

        tv_nohavevillage= (TextView) headerView.findViewById(R.id.tv_nohavevillage);
        rv_myvillage= (RecyclerView) headerView.findViewById(R.id.rv_myvillage);
        rv_myvillage.setLayoutManager(getLayoutManager());
        rv_myvillage.addItemDecoration(getDefaultItemDecoration());
        mMyVillageAdapter = new MyVillageAdapter(mMyVillages);
        rv_myvillage.setAdapter(mMyVillageAdapter);

        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        headerView.setLayoutParams(params);
        mNearVillageAdapter.setHeaderView(headerView);
        mNearVillageAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Village village = mVillages.get(position);
                MyApplication.houseid=village.getId();
                MyApplication.houseName=village.getHousingName();
                Intent intent = new Intent();
                intent.setAction(Constant.BROADCAST_CHOICE_VILLAGE);
                sendBroadcast(intent);
                setResult(RESULT_OK);
                finish();
            }
        });
        mMyVillageAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                MyVillage village = mMyVillages.get(position);
                MyApplication.houseid=village.getHousingId();
                MyApplication.houseName=village.getHousingName();
                Intent intent = new Intent();
                intent.setAction(Constant.BROADCAST_CHOICE_VILLAGE);
                sendBroadcast(intent);
                setResult(RESULT_OK);
                finish();
            }
        });
        return mNearVillageAdapter;
    }

    private void loadMore() {
        pageNo++;
        getData();
    }

    private void pullDownRefresh() {
        pageNo = 0;
        getData();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 设置刷新状态
     * @param refreshing 刷新状态
     */
    public void setRefreshing(boolean refreshing){
        mSwipeRefreshLayout.setRefreshing(refreshing);
    }

    protected void setLoadMoreText(CharSequence text){
        mSwipeRefreshLayout.setLoadMoreText(text);
    }
    protected RecyclerView.ItemDecoration getDefaultItemDecoration(){
        return defaultItemDecoration;
    }
    /**
     * 添加分割线，可以是多种。比如网格的横竖2中分割线，不会覆盖。
     * @param itemDecoration 分割线
     */
    protected void addItemDecoration(RecyclerView.ItemDecoration itemDecoration){
        if (itemDecoration==null){
            return;
        }
        mSwipeRefreshLayout.addItemDecoration(itemDecoration);
    }
    /**
     * @return  默认垂直布局。
     */
    protected RecyclerView.LayoutManager getLayoutManager(){
        return new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
    }
    /**
     * @return 默认上拉下拉同时存在
     */
    protected SwipeRefreshRecyclerLayout.Mode getMode(){
        return SwipeRefreshRecyclerLayout.Mode.Both;
    }

    @OnClick({R.id.iv_accoutlogin_delete,R.id.tv_tosearchvillage})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_accoutlogin_delete:
                //描述:结束选择小区界面
                finish();
                break;
            case R.id.tv_tosearchvillage:
                //描述:到搜索小区界面
                ActivityUtil.create(mContext).go(SearchVillageActivity.class)
                        .startForResult(3);

                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            switch (requestCode){
                case 3:
                    if(data!=null){
                        MyApplication.houseid=data.getStringExtra("housingId");
                        MyApplication.houseName=data.getStringExtra("housingName");
                        Intent intent = new Intent();
                        intent.setAction(Constant.BROADCAST_CHOICE_VILLAGE);
                        sendBroadcast(intent);
                        setResult(RESULT_OK);
                    }
                    finish();
                    break;
            }
        }
    }
}
